If (elif, else)

This is probably the most used conditional structure in programming. Here is the syntax in Python


In [ ]:
a = 1
b = 4

if a < b:
    print('a is smaller than b')
elif a > b:
    print('a is larger than b')
else:
    print('a is equal to b')

Important: the lines of code after the if, elif, else statement have to be indented by 4 spaces to indicate that they are part of the same instructions block.

The table below includes some of the operators that can be used inside the if conditions. They all return a boolean variable (True or False).

Operator Meaning
== Equal to
!= Not equal
< Smaller than
> Larger than
<= Smaller-equal than
>= Larger-equal than
not Logiccal Negation
in Checks whether an element is in a list
and Checks whether two conditions are True
or Checks whether at least one condition is True
is Checks whether an elemenent is equal to another.

Let see some examples:


In [ ]:
5 in [1, 2, 4]

In [ ]:
3 in [1, 2, 3]

In [ ]:
not (2 == 5)

while

This control structure also checks for a condition to be True in order to execute a series of instructions. The 4 space rule for indentantion also applies.


In [ ]:
a = []
while len(a) < 10:
    a.append(0) # add elements to the list until I have 10.
print(a)

In [ ]:
# This is an example of random walk.
import random

position = 0
n_steps = 0
while abs(position) < 10: # I will walk until I am a distance of 10
    step = 2.0*(random.random()-0.5) # this is a random variable between -1 and 1
    position += step
    n_steps += 1
    
print(position, n_steps) # this is the final position and the number of steps

Exercise 1.1

Compute how many times, on average, do you have to throw a die (with only six faces) in order to reach reach a minimum of 100 points. In this game you start with 0 points, you throw the die and if you get a 4 then you add 4 points into your account. Use the results of random.random() to implement the die throw.


In [ ]: